/*
 * ListeningSocket.cpp
 *
 *  Created on: Nov 2, 2012
 *      Author: lucas
 */

#include "ListeningSocket.h"

#include <netdb.h>
#include <cstring>
#include <errno.h>
#include <iostream>

#define BACKLOG 20


CommunicationSocket* ListeningSocket::aceptar() {
	int newSocket;

	if (validSocket && listening) {
		 newSocket = accept(sockfd, NULL, 0);
		 if (newSocket != -1)
			 return new CommunicationSocket(newSocket);
	}
	return 0;
}

bool ListeningSocket::escuchar() {
	struct sockaddr_in my_addr;
	int ret;

	if (validSocket && !listening) {
		// hago el bind
		my_addr.sin_family = AF_INET;
		my_addr.sin_port = htons(puerto);
		my_addr.sin_addr.s_addr = INADDR_ANY;
		memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero));
		ret = bind(sockfd, (struct sockaddr*)&my_addr, sizeof(my_addr));
		if (ret == -1) {
			std::cerr << "ListeningSocket::escuchar() - ERROR " << errno <<
					": " << strerror(errno) << std::endl;
			return false;
		}

		// hago el listen
		ret = listen(sockfd, BACKLOG);
		if (ret == -1) {
			std::cerr << "ListeningSocket::escuchar() - ERROR " <<
					errno << ": " << strerror(errno) << std::endl;
			return false;
		}
		listening = true;
		return true;
	}
	return false;
}

bool ListeningSocket::escuchando() {
	return listening;
}



ListeningSocket::~ListeningSocket() {
}

